import i18n from "@/lang";
import { tunnyRequest, pandaRequest } from "@/utils/request";
import { decrypt, encrypt } from '@/utils/auth';
import { deepClone } from "@/utils";

// import { createService } from "@/utils/request";
// import { AppModule } from '../store/modules/app';

// const tunnyApi = (options: any) => createService(AppModule.baseURL)(options);
// const pandaRequest = (options: any) => createService(AppModule.baseURL)(options);

export default class PandaApi {
  public getBaseURL() {
    return pandaRequest({
      url: "/frontdesk",
      method: "GET",
    });
  }

  /**
   * 获取桌面池数据
   * @param params 分页数据
   */
  public async getDesktopPools(
    params: any
  ) {
    const res: any = await pandaRequest({
      url: "desktop_pools",
      method: "GET",
      params
    });
    // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
    //   if (row.name) {
    //     row.name = decrypt(row.name);
    //   }
    //   (res.rows ? res.rows : res)[rowsIndex] = row;
    // });
    return res;
  }

  /**
   * 获取桌面池详情
   * @param params 分页数据
   */
  public getDesktopPoolInfo(
    poolId: any
  ) {
    return pandaRequest({
      url: `/desktop_pools/${poolId}`,
      method: "GET"
    });
  }

  /**
   * 同步Horizon桌面池
   */
  public syncHorizonDesktopPools(resource_pool_id: any, desktopPoolId: any) {
    return pandaRequest({
      url: "resource_pools/" + resource_pool_id +"/st_resources/" + desktopPoolId +"/sync",
      method: "POST"
    });
  }

  /**
   * 同步DaaS桌面池
   */
  public syncDaaSDesktopPools(resource_pool_id: any, desktopPoolId: any) {
    return pandaRequest({
      url: "resource_pools/" + resource_pool_id +"/mt_resources/" + desktopPoolId +"/sync",
      method: "POST"
    });
  }

  /**
   * 同步租户桌面
   */
  public syncDesktops(type: any) {
    return pandaRequest({
      url: "/desktops/sync",
      method: "POST",
      data: {
        resource_type: type
      }
    });
  }

  /**
   * 搜索桌面
   */
  public searchDesktops(params: any) {
    return pandaRequest({
      url: "desktops/search",
      method: "GET",
      params
    })
  }

  /**
   * 操作桌面池中的桌面
   * @param poolId 桌面池id 
   */

  public desktopOperation(poolId: string, params: any) {
    return pandaRequest({
      url: "desktop_pools/" + poolId + "/desktops/action",
      method: "POST",
      data: {
        ids: params.ids,
        action: params.action,
        message: params.message,
        message_type: params.message_type
      }
    });
  }

    /**
   * 获取桌面池中的桌面
   * @param poolType 桌面池类型
   * @param poolId 桌面池id
   */
  public getDesktops(poolId: string, params: any) {
    return pandaRequest({
      url:  "desktop_pools/" + poolId + "/desktops",
      method: "GET",
      params
    });
  }

    /**
   * 修改桌面池中的桌面
   * @param poolType 桌面池类型
   * @param poolId 桌面池id
   */
    public patchDesktops(poolId: string, desktopId: string, params: any) {
    return pandaRequest({
      url:  "desktop_pools/" + poolId + "/desktops/" + desktopId,
      method: "PATCH",
      data: {
        usb_rule_group: params.usb_rule_group
      }
    });
  }

  /**
   * 修改桌面别名
   */
   public apiPatchDesktops(poolId: string, desktopId: string, data: any) {
    return pandaRequest({
      url:  "desktop_pools/" + poolId + "/desktops/" + desktopId,
      method: "PATCH",
      data
    });
  }

  /**
   * 根据桌面类型获取桌面
   */
  public getTenantsDesktops(params: any) {
    return pandaRequest({
      url:  "/desktops/sort",
      method: "GET",
      params
    });
  }

  /**
   * 建立桌面授权关系
   * @param desktopId 桌面id
   * @param data 其他参数
   */
  public buildDesktopAuth(desktopId: string, data: any) {
    return pandaRequest({
      url: "desktops/" + desktopId + "/assign_users",
      method: "PUT",
      data
    });
  }

  /**
   * 解除桌面授权
   * @param desktopId 桌面id
   * @param data 解除用的数据
   */
  public relieveDesktopAuth(desktopId: string, data: any) {
    return pandaRequest({
      url: "desktops/" + desktopId + "/unassign_users",
      method: "PUT",
      data
    });
  }

    /**
   * 获取桌面数量
   * @param tenant_id 用户id
   */
     public getDesktopCount(tenant_id: any) {
      return pandaRequest({
        url: "tenant/desktops/statistics",
        method: "GET",
        params: {
          "cloud_tenant_ids": "[" + tenant_id + "]"
        }
      });
    }




  // 查看usb规则组列表,新建桌面、编辑桌面等下拉框中用到
  public apiListUsbRuleGroups() {
    return pandaRequest({
      url: "/usb_rule_groups",
      method: "get"
    });
  }

  // usb规则组的表格查询接口
  public async apiGetUsbRuleGroupsByPage(pageQuery: any) {
    const res: any = await pandaRequest({
      url: "/usb_rule_groups",
      method: "get",
      params: pageQuery
    });
    // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
    //   if (row.cloud_tenant_name) {
    //     row.cloud_tenant_name = decrypt(row.cloud_tenant_name);
    //   }
    //   (res.rows ? res.rows : res)[rowsIndex] = row;
    // });
    return res;
  }

  // 查看usb规则组详情
  public apiGetUsbRuleGroup(id: string) {
    return pandaRequest({
      url: "/usb_rule_groups/" + id,
      method: "get"
    });
  }

  // 查看usb规则组列表
  public apiListUsbRuleGroupsPaged(limit: number, offset: string, search: string) {
    return pandaRequest({
      url:
        "/usb_rule_groups?limit=" +
        limit +
        "&offset=" +
        offset +
        "&search=" +
        search,
      method: "get"
    });
  }

  // 增加usb规则组
  public apiAddUsbRuleGroup(params: any) {
    return pandaRequest({
      url: "/usb_rule_groups",
      method: "post",
      data: params
    });
  }

  // 删除usb规则组
  public apiDeleteUsbRuleGroup(id: number) {
    return pandaRequest({
      url: "/usb_rule_groups/" + id,
      method: "delete"
    });
  }

  // 修改usb规则组
  public apiUpdateUsbRuleGroup(id: number, params: any) {
    return pandaRequest({
      url: "/usb_rule_groups/" + id,
      method: "patch",
      data: params
    });
  }

  // 查看所有usb规则组名称列表,防止重名
  public apiGetAllUsbRuleGroupNames() {
    return pandaRequest({
      url: "/usb_rule_groups/names/used",
      method: "get"
    });
  }

  // 查看所有当前规则组下的规则列表
  public apiListUsbRulesPaged(policyId: number, pageQuery: any) {
    return pandaRequest({
      url: "/usb_rule_groups/" + policyId + "/usb_rules",
      method: "get",
      params: pageQuery
    });
  }

  // 增加usb规则
  public apiAddUsbRule(id: number, params: any) {
    return pandaRequest({
      url: "/usb_rule_groups/" + id + "/usb_rules",
      method: "post",
      data: params
    });
  }

  // 删除usb规则
  public apiDeleteUsbRule(group_id: number, rule_id: number) {
    return pandaRequest({
      url: "/usb_rule_groups/" + group_id + "/usb_rules/" + rule_id,
      method: "delete"
    });
  }

  // 修改usb规则
  public apiUpdateUsbRule(group_id: number, rule_id: number, params: any) {
    return pandaRequest({
      url: "/usb_rule_groups/" + group_id + "/usb_rules/" + rule_id,
      method: "patch",
      data: params
    });
  }

  // 是否允许usb规则透传
  public apiEnableUsbRule(group_id: number, rule_id: number, enabled: boolean) {
    return pandaRequest({
      url: "/usb_rule_groups/" + group_id + "/usb_rules/" + rule_id,
      method: "patch",
      data: {
        enabled
      }
    });
  }

  // 下载中心列表: 下载链接、图标、描述等
  public apiGetDownloads() {
    return pandaRequest({
      url: "/downloads/",
      method: "get"
    });
  }

  // 查看许可证信息
  public apiGetLicense() {
    return pandaRequest({
      url: "/license",
      method: "get"
    });
  }

  // 导入许可证
  public apiImportLicense(license: any) {
    return pandaRequest({
      url: "/license",
      method: "post",
      data: license
    });
  }

  // 备份设置
  public apiGetBackupSettings() {
    return pandaRequest({
      url: "/backups/settings/",
      method: "get"
    });
  }

  public apiCreateBackup() {
    return pandaRequest({
      url: "/backups",
      method: "post"
    });
  }

  public apiRecoverFromBackup(backupName: string) {
    return pandaRequest({
      url: "/backups/" + backupName + "/recover/",
      method: "patch"
    });
  }

  public async apiGetBackupsList(params: any) {
    const result: any = await pandaRequest({
      url: "/backups",
      method: "get"
    });

    const total = result.data.length;
    const rows = result.data.splice((params.page - 1) * params.page_size, params.page_size);

    return {
      rows,
      total,
      db_migration_index: result.db_migration_index
    }
  }

  public apiDownloadBackup(backup_name: any) {
    return pandaRequest({
      url: "/backups/" + backup_name + "/download/",
      method: "get"
    });
  }

  public apiSetBackupSettings(data: any) {
    return pandaRequest({
      url: "/backups/settings/",
      method: "patch",
      data
    });
  }

  public async apiBatchDeleteBackup(backupList: Array<any>) {
    for (let i = 0; i < backupList.length; i++) {
      await pandaRequest({
        url: "/backups",
        method: "delete",
        data: {
          backup_name: backupList[i].backup_name
        }
      });
    }
    return true;
  }

  /**
   * 向桌面发指令
   * @param id 桌面id
   * @param data 指令数据
   */
  public apiActiveDesktop(id: any, data: any) {
    return pandaRequest({
      url: "/desktops/" + id + "/action",
      method: "POST",
      data
    });
  }

  /**
   * 获取桌面控制台url
   * @param id 桌面id
   * @param data 请求数据
   */
  public apiGetDesktopConsoleUrl(id: any, data: any) {
    return pandaRequest({
      url: "/desktops/" + id + "/console",
      method: "POST",
      data
    });
  }

  /**
   * 设置桌面授权信息
   * @param id 桌面id
   * @param data 授权数据
   */
  public apiAuthDesktop(id: any, data: any) {
    return pandaRequest({
      url: "desktops/" + id + "/auth",
      method: "POST",
      data
    });
  }

  /**
   * 获取系统配置
   */
  public async apiGetSystemSettings() {
    const res: any = await pandaRequest({
      url: "/panda_settings/",
      method: "get"
    });

    /**
     * 对邮箱手机做解密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
    if (res.global_desktop_exceptions_notice_mobiles) {
      try {
        res.global_desktop_exceptions_notice_mobiles = JSON.parse(decrypt(res.global_desktop_exceptions_notice_mobiles));
      } catch (error) {
        res.global_desktop_exceptions_notice_mobiles = [];
      }
      // res.global_desktop_exceptions_notice_mobiles.forEach((mobile: string, index: number) => res.global_desktop_exceptions_notice_mobiles[index] = decrypt(mobile));
    }
    if (res.global_desktop_exceptions_notice_mails) {
      try {
        res.global_desktop_exceptions_notice_mails = JSON.parse(decrypt(res.global_desktop_exceptions_notice_mails));
      } catch (error) {
        res.global_desktop_exceptions_notice_mails = [];
      }
      // res.global_desktop_exceptions_notice_mails.forEach((mail: string, index: number) => res.global_desktop_exceptions_notice_mails[index] = decrypt(mail));
    }

    return res;
  }

  /**
   * 获取系统终端的FAQ配置
   */
   public apiGetSettings() {
    return pandaRequest({
      url: "/settings/",
      method: "get"
    });
  }
  /**
   * 更新系统终端的FAQ配置
   */
   public apiPatchSettings(data: any) {
    return pandaRequest({
      url: "/settings/",
      method: "patch",
      data
    });
  }

  /**
   * 获取系统mesh配置
   */
  public async apiGetMeshSettings() {
    const res: any = await pandaRequest({
      url: "/panda_settings/",
      method: "get"
    });

    /**
     * 对邮箱手机做解密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
    // if (res.global_desktop_exceptions_notice_mobiles) {
    //   try {
    //     res.global_desktop_exceptions_notice_mobiles = JSON.parse(decrypt(res.global_desktop_exceptions_notice_mobiles));
    //   } catch (error) {
    //     res.global_desktop_exceptions_notice_mobiles = [];
    //   }
    //   // res.global_desktop_exceptions_notice_mobiles.forEach((mobile: string, index: number) => res.global_desktop_exceptions_notice_mobiles[index] = decrypt(mobile));
    // }
    // if (res.global_desktop_exceptions_notice_mails) {
    //   try {
    //     res.global_desktop_exceptions_notice_mails = JSON.parse(decrypt(res.global_desktop_exceptions_notice_mails));
    //   } catch (error) {
    //     res.global_desktop_exceptions_notice_mails = [];
    //   }
    //   // res.global_desktop_exceptions_notice_mails.forEach((mail: string, index: number) => res.global_desktop_exceptions_notice_mails[index] = decrypt(mail));
    // }

    return res;
  }

  /**
   * 保存系统配置
   */
  public apiSaveSystemSettings(_data: any) {
    /**
     * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
     */
    const data = deepClone(_data);

    // if (data.global_desktop_exceptions_notice_mobiles) {
    //   data.global_desktop_exceptions_notice_mobiles = data.global_desktop_exceptions_notice_mobiles.split(',');

    //   if (data.global_desktop_exceptions_notice_mobiles.length > 0) {
    //     data.global_desktop_exceptions_notice_mobiles = encrypt(JSON.stringify(data.global_desktop_exceptions_notice_mobiles));
    //     // data.global_desktop_exceptions_notice_mobiles.forEach((mobile: string, index: number) => data.global_desktop_exceptions_notice_mobiles[index] = encrypt(mobile));
    //   }
    // } else {
    //   data.global_desktop_exceptions_notice_mobiles = encrypt("[]");
    // }

    // if (data.global_desktop_exceptions_notice_mails) {
    //   data.global_desktop_exceptions_notice_mails = data.global_desktop_exceptions_notice_mails.split(',');

    //   /**
    //    * 邮箱手机号加密，用map遍历修改没有生效，先用forEach了，以后再探究
    //    * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
    //    */
    //   if (data.global_desktop_exceptions_notice_mails.length > 0) {
    //     data.global_desktop_exceptions_notice_mails = encrypt(JSON.stringify(data.global_desktop_exceptions_notice_mails));
    //     // data.global_desktop_exceptions_notice_mails.forEach((mail: string, index: number) => data.global_desktop_exceptions_notice_mails[index] = encrypt(mail));
    //   }
    // } else {
    //   data.global_desktop_exceptions_notice_mails = encrypt("[]");
    // }
    
    return pandaRequest({
      url: "/panda_settings/",
      method: "PATCH",
      data: {
        settings: data
      }
    });
  }

  /**
   * 分页获取多条会话
   * @param params 分页参数
   */
  public async apiGetSessions(params: any) {
    const res: any =  await pandaRequest({
      url: "/desktop_sessions",
      method: "GET",
      params
    });
    // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
    //   if (row.cloud_tenant_name) {
    //     row.cloud_tenant_name = decrypt(row.cloud_tenant_name);
    //   }
    //   if (row.user_name) {
    //     row.user_name = decrypt(row.user_name);
    //   }
    //   (res.rows ? res.rows : res)[rowsIndex] = row;
    // });
    return res;
  }

  /**
   * 断开会话
   * @param params 
   */
   public apiDisconnectSessions(data: any, id: any) {
    return pandaRequest({
      url: "/desktop_pools/" + id + "/desktops/action",
      method: "POST",
      data
    });
  }

  // /**
  //  * 分页获取多条历史会话
  //  * @param params 分页参数
  //  */
  // public apiGetHistorySessions(params: any) {
  //   return pandaRequest({
  //     url: "/history_sessions",
  //     method: "GET",
  //     params
  //   });
  // }

  // /**
  //  * 删除历史会话
  //  */
  // public apiDeleteHistorySessions() {
  //   return pandaRequest({
  //     url: "/history_sessions",
  //     method: "DELETE"
  //   });
  // }

  /**
   * 分页获取多条终端数据
   * @param params 分页传入参数
   */
  public async apiGetClients(params: any) {
    const res:any = await pandaRequest({
      url: "/desktop_clients",
      method: "GET",
      params
    });
    // (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
    //   if (row.cloud_tenant_name) {
    //     row.cloud_tenant_name = decrypt(row.cloud_tenant_name);
    //   }
    //   (res.rows ? res.rows : res)[rowsIndex] = row;
    // });
    return res;
  }

  /**
 * 获取终端列表
 */
  public apiGetClientListByPageSize = async (page: any, page_size: any, cloud_tenant_id: any, search_data?: any) => {
  return await pandaRequest({
    url: "/desktop_clients?page=" + page + "&page_size=" + page_size + "&search=" + search_data + "&cloud_tenant_id=" + cloud_tenant_id,
    method: "GET",
    params: {}
  });
}

  /**
   * 获取一条终端的详情数据
   * @param id 终端ID
   */
  public apiGetClient(id: number) {
    return pandaRequest({
      url: "/desktop_clients/" + id,
      method: "GET"
    });
  }

  /**
   * 更新一条终端数据
   * @param id 终端ID
   * @param data 新的终端数据
   */
  public apiPatchClient(id: number, data: any) {
    return pandaRequest({
      url: "/desktop_clients/" + id,
      method: "PATCH",
      data
    });
  }

  /**
   * 批量更新一条终端数据
   * @param id 终端ID
   * @param data 新的终端数据
   */
  public apiBatchPatchClient(ids: any, data: any) {
    const allRequests = ids.map((id: any) => {
      return pandaRequest({
        url: "/desktop_clients/" + id,
        method: "PATCH",
        data
      });
    });
    return Promise.all(allRequests);
  }

  /**
   * 删除一条终端数据
   * @param id 终端ID
   */
  public apiDeleteClient(id: number) {
    return pandaRequest({
      url: "/desktop_clients/" + id,
      method: "DELETE"
    });
  }

  /**
   * 批量删除终端
   */
  public apiBatchDeleteClient(clientList: Array<any>) {
    const allRequests = clientList.map((client: any) => {
      return pandaRequest({
        url: "/desktop_clients/" + client.id,
        method: "DELETE"
      });
    });

    return Promise.all(allRequests);
  }

  /**
   * 批量操作终端数据
   * @param data 传值
   */
  public apiBatchActionClient(data: any) {
    return pandaRequest({
      url: "/desktop_clients/batch_action/",
      method: "POST",
      data
    });
  }

  /**
   * 分页获取多条终端版本
   * @param params 分页参数
   */
  public apiGetClientVersions(params: any) {
    return pandaRequest({
      url: "/versions",
      method: "GET",
      params
    });
  }

  /**
   * 通过ID获取终端版本详情
   * @param id
   */
  public apiGetClientVersion(id: any) {
    return pandaRequest({
      url: "/versions/" + id,
      method: "GET"
    });
  }

  /**
   * 通过ID更新终端版本
   * @param id
   * @param data
   */
  public apiPatchClientVersion(id: any, data: any) {
    return pandaRequest({
      url: "/versions/" + id,
      method: "PATCH",
      data
    });
  }

  /**
   * 通过ID删除终端版本
   * @param data
   */
  public apiDeleteClientVersion(data: any) {
    const allRequests = data.map((version: any) => {
      return pandaRequest({
        url: "/versions/" + version.id,
        method: "DELETE"
      });
    });

    return Promise.all(allRequests);
  }

  /**
   * 通过文件名上传终端版本
   * @param filename
   * @param data
   */
  public apiUploadClientVersion(filename: any, data: any, cancelToken: any, headers: any) {
    return pandaRequest({
      url: "/versions/" + filename + "/upload",
      method: "PUT",
      data,
      headers,
      cancelToken
    });
  }

  /**
   * 获取资源池接口
   */
  public async apiGetResourceList(params: any) {
    const res: any = await pandaRequest({
      url: "/resource_pools",
      method: 'GET',
      params
    });

    /**
     * 对资源池数据中的邮箱手机和ip地址做解密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
    (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
      if (row.desktop_exceptions_notice_mail) {
        try {
          row.desktop_exceptions_notice_mail = JSON.parse(decrypt(row.desktop_exceptions_notice_mail));
        } catch (error) {
          row.desktop_exceptions_notice_mail = [];
        }
        // row.desktop_exceptions_notice_mail.forEach((mail: string, index: number) => row.desktop_exceptions_notice_mail[index] = decrypt(mail));
      }
      if (row.desktop_exceptions_notice_mobile) {
        try {
          row.desktop_exceptions_notice_mobile = JSON.parse(decrypt(row.desktop_exceptions_notice_mobile));
        } catch (error) {
          row.desktop_exceptions_notice_mobile = [];
        }
        // row.desktop_exceptions_notice_mobile.forEach((mobile: string, index: number) => row.desktop_exceptions_notice_mobile[index] = decrypt(mobile));
      }
      if (row.api_proxy) {
        row.api_proxy = decrypt(row.api_proxy);
      }
      (res.rows ? res.rows : res)[rowsIndex] = row;
    });

    return res;
  }

  /**
   * 获取资源池下的资源租户
   * @param params 
   * @
   */
  public async apiGetResourceTenantsList(resourcePoolId: any, params: any) {
    return pandaRequest({
      url: 'resource_pools/' + resourcePoolId + '/resources/summary',
      method: 'GET',
      params
    })
  }

  /**
   * 获取资源池详情接口
   */
  public async apiGetResourceInfo(id: any) {
    const res: any =  await pandaRequest({
      url: "/resource_pools/" + id,
      method: 'GET'
    });

    /**
     * 对资源池数据中的邮箱手机和ip地址做解密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
    if (res.desktop_exceptions_notice_mail) {
      try {
        res.desktop_exceptions_notice_mail = JSON.parse(decrypt(res.desktop_exceptions_notice_mail));
      } catch (error) {
        res.desktop_exceptions_notice_mail = [];
      }
      // res.desktop_exceptions_notice_mail.forEach((mail: string, index: number) => res.desktop_exceptions_notice_mail[index] = decrypt(mail));
    }
    if (res.desktop_exceptions_notice_mobile) {
      try {
        res.desktop_exceptions_notice_mobile = JSON.parse(decrypt(res.desktop_exceptions_notice_mobile));
      } catch (error) {
        res.desktop_exceptions_notice_mobile = [];
      }
      // res.desktop_exceptions_notice_mobile.forEach((mobile: string, index: number) => res.desktop_exceptions_notice_mobile[index] = decrypt(mobile));
    }
    if (res.api_proxy) {
      res.api_proxy = decrypt(res.api_proxy);
    }

    return res;
  }

  /**
   * 创建资源池接口
   */
  public apiPostResourceList(_data: any) {
    /**
     * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
     */
    const data = deepClone(_data);

    /**
     * 对资源池数据中的邮箱手机和ip地址做加密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
    if (data.desktop_exceptions_notice_mail.length > 0) {
      try {
        data.desktop_exceptions_notice_mail = encrypt(JSON.stringify(data.desktop_exceptions_notice_mail));
      } catch (error) {
        data.desktop_exceptions_notice_mail = [];
      }
      // data.desktop_exceptions_notice_mail.forEach((mail: string, index: number) => data.desktop_exceptions_notice_mail[index] = encrypt(mail));
    }
    if (data.desktop_exceptions_notice_mobile.length > 0) {
      try {
        data.desktop_exceptions_notice_mobile = encrypt(JSON.stringify(data.desktop_exceptions_notice_mobile));
      } catch (error) {
        data.desktop_exceptions_notice_mobile = [];
      }
      // data.desktop_exceptions_notice_mobile.forEach((mobile: string, index: number) => data.desktop_exceptions_notice_mobile[index] = encrypt(mobile));
    }
    if (data.api_proxy) {
      data.api_proxy = encrypt(data.api_proxy);
    }
    return pandaRequest({
      url: "/resource_pools",
      method: 'POST',
      data
    });
  }

  /**
   * 编辑资源池接口
   */
  public apiPutResourceList(id: any, _data: any) {
    /**
     * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
     */
    const data = deepClone(_data);

    /**
     * 对资源池数据中的邮箱手机和ip地址做加密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
    if (data.desktop_exceptions_notice_mail.length > 0) {
      try {
        data.desktop_exceptions_notice_mail = encrypt(JSON.stringify(data.desktop_exceptions_notice_mail));
      } catch (error) {
        data.desktop_exceptions_notice_mail = [];
      }
      // data.desktop_exceptions_notice_mail.forEach((mail: string, index: number) => data.desktop_exceptions_notice_mail[index] = encrypt(mail));
    }
    if (data.desktop_exceptions_notice_mobile.length > 0) {
      try {
        data.desktop_exceptions_notice_mobile = encrypt(JSON.stringify(data.desktop_exceptions_notice_mobile));
      } catch (error) {
        data.desktop_exceptions_notice_mobile = [];
      }
      // data.desktop_exceptions_notice_mobile.forEach((mobile: string, index: number) => data.desktop_exceptions_notice_mobile[index] = encrypt(mobile));
    }
    if (data.api_proxy) {
      data.api_proxy = encrypt(data.api_proxy);
    }
    return pandaRequest({
      url: "/resource_pools/" + id,
      method: 'PUT',
      data
    });
  }

  /**
   * 删除资源池接口
   */
  public apiBatchDeleteResourcePool(resourceList: Array<any>) {
    const allRequests = resourceList.map((resource: any) => {
      return pandaRequest({
        url: "/resource_pools/" + resource.id,
        method: "DELETE"
      });
    });

    return Promise.all(allRequests);
  }

  /**
   * 批量删除Horizon资源池接口
   */
  public apiBatchDeleteHorizonResourcePools(pool_id: any, resourceList: Array<any>) {
    const allRequests = resourceList.map((resource: any) => {
      return pandaRequest({
        url: `resource_pools/${ pool_id }/st_resources/${resource.id}`,
        method: "DELETE"
      });
    });

    return Promise.all(allRequests);
  }

  /**
   * 批量删除Daas资源池接口
   */
  public apiBatchDeleteDaasResourcePools(pool_id: any, resourceList: Array<any>) {
    const allRequests = resourceList.map((resource: any) => {
      return pandaRequest({
        url: `resource_pools/${ pool_id }/mt_resources/${resource.id}`,
        method: "DELETE"
      });
    });

    return Promise.all(allRequests);
  }

  /**
   * 获取普通版租户列表接口
   */
  public async apiGetHorizonTenantList(params: any) {
    const res: any = await pandaRequest({
      url: `resource_pools/${ params.pool_id }/st_resources`,
      method: 'GET',
      params
    });
    /**
     * 对资源池数据中的邮箱手机和ip地址做解密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
     (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
      if (row.api_proxy) {
        row.api_proxy = decrypt(row.api_proxy);
      }
      // if(row.ad_info) {
      //   if(row.ad_info.server_uri) {
      //     row.ad_info.server_uri = decrypt(row.ad_info.server_uri);
      //   }
      //   if(row.ad_info.bind_dn) {
      //     row.ad_info.bind_dn = decrypt(row.ad_info.bind_dn);
      //   }
      //   if(row.ad_info.bind_password) {
      //     row.ad_info.bind_password = decrypt(row.ad_info.bind_password);
      //   }
      // }
      // if(row.connection_info) {
      //   if(row.connection_info.gateway) {
      //     row.connection_info.gateway = decrypt(row.connection_info.gateway);
      //   }
      //   if(row.connection_info.default_domain) {
      //     row.connection_info.default_domain = decrypt(row.connection_info.default_domain);
      //   }
      //   if(row.connection_info.server_url) {
      //     row.connection_info.server_url = decrypt(row.connection_info.server_url);
      //   }
      // }
      // if(row.credential) {
      //   if(row.credential.username) {
      //     row.credential.username = decrypt(row.credential.username);
      //   }
      //   if(row.credential.password) {
      //     row.credential.password = decrypt(row.credential.password);
      //   }
      // }
      // if(row.uri) {
      //   row.uri = decrypt(row.uri);
      // }
      (res.rows ? res.rows : res)[rowsIndex] = row;
    });
    return res;
  }

  /**
   * 添加普通版租户接口
   */
  public apiPostHorizonTenantList(_data: any) {
    /**
     * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
     */
    const data = deepClone(_data);

    if (data.basicFormData && data.basicFormData.api_proxy) {
      data.basicFormData.api_proxy = encrypt(data.basicFormData.api_proxy);
    }

    return pandaRequest({
      url: `resource_pools/${ data.poolId }/st_resources`,
      method: 'POST',
      data: {
        name: data.basicFormData.name,
        availability_zone: data.basicFormData.availability_zone,
        uri: data.basicFormData.manage_address,
        platform_uuid: data.basicFormData.platform_uuid,
        api_proxy: data.basicFormData.api_proxy,
        credential: {
          username: data.basicFormData.manage_account,
          password: data.basicFormData.manage_password
          // password: encrypt(data.basicFormData.manage_password)
        },
        connection_info: {
          gateway: data.basicFormData.desktop_getaway_address
        },
        ad_info: {
          server_uri: data.adFormData.ad_adress,
          bind_dn: data.adFormData.ad_account,
          bind_password: data.adFormData.ad_password,
          search_base_dn: data.adFormData.ad_dn,
          search_filter: data.adFormData.ad_filiter
        },
       }
    });
  }

    /**
   * 编辑普通版租户接口
   */
     public apiPutHorizonTenantList(_data: any) {
       /**
        * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
        */
      const data = deepClone(_data);

      if (data.basicFormData && data.basicFormData.api_proxy) {
        data.basicFormData.api_proxy = encrypt(data.basicFormData.api_proxy);
      }

      return pandaRequest({
        url: `resource_pools/${ data.poolId }/st_resources/${ data.id }`,
        method: 'PATCH',
        data: {
          name: data.basicFormData.name,
          availability_zone: data.basicFormData.availability_zone,
          platform_uuid: data.basicFormData.platform_uuid,
          api_proxy: data.basicFormData.api_proxy,
          uri: data.basicFormData.manage_address,
          credential: {
            username: data.basicFormData.manage_account,
            password: data.basicFormData.manage_password
          // password: encrypt(data.basicFormData.manage_password)
          },
          connection_info: {
            gateway: data.basicFormData.desktop_getaway_address
          },
          ad_info: {
            server_uri: data.adFormData.ad_adress,
            bind_dn: data.adFormData.ad_account,
            bind_password: data.adFormData.ad_password,
            search_base_dn: data.adFormData.ad_dn,
            search_filter: data.adFormData.ad_filiter
          },
         }
      });
    }

  /**
   * 获取旗舰&GPU版租户列表接口
   */
  public async apiGetDaaSTenantList(params: any) {
    const res: any = await pandaRequest({
      url: `/resource_pools/${ params.pool_id }/mt_resources`,
      method: 'GET',
      params
    });

    /**
     * 对资源池数据中的邮箱手机和ip地址做解密
     * 后端把数据格式改成了字符串，没时间改view层了，只能在这边把数组再转回字符串
     */
     (res.rows ? res.rows : res).forEach((row: any, rowsIndex: number) => {
      if (row.api_proxy) {
        row.api_proxy = decrypt(row.api_proxy);
      }
      // if(row.ad_info) {
      //   if(row.ad_info.server_uri) {
      //     row.ad_info.server_uri = decrypt(row.ad_info.server_uri);
      //   }
      //   if(row.ad_info.bind_dn) {
      //     row.ad_info.bind_dn = decrypt(row.ad_info.bind_dn);
      //   }
      //   if(row.ad_info.bind_password) {
      //     row.ad_info.bind_password = decrypt(row.ad_info.bind_password);
      //   }
      // }
      // if(row.connection_info) {
      //   if(row.connection_info.gateway) {
      //     row.connection_info.gateway = decrypt(row.connection_info.gateway);
      //   }
      //   if(row.connection_info.default_domain) {
      //     row.connection_info.default_domain = decrypt(row.connection_info.default_domain);
      //   }
      //   if(row.connection_info.server_url) {
      //     row.connection_info.server_url = decrypt(row.connection_info.server_url);
      //   }
      // }
      // if(row.credential) {
      //   if(row.credential.username) {
      //     row.credential.username = decrypt(row.credential.username);
      //   }
      //   if(row.credential.password) {
      //     row.credential.password = decrypt(row.credential.password);
      //   }
      // }
      // if(row.cloud_tenant_name) {
      //   row.cloud_tenant_name = decrypt(row.cloud_tenant_name)
      // }
      (res.rows ? res.rows : res)[rowsIndex] = row;
    });
    return res;
  }

  /**
   * 用户页面
   */
  public apiGetResourceInfoInUser(resource_type: any, resource_id: any) {
    if (resource_type === "HorizonView") {
      return pandaRequest({
        url: `/st_resources/${resource_id}`,
        method: "GET"
      });
    } else if (resource_type === "HorizonDaas") {
      return pandaRequest({
        url: `/mt_resources/${resource_id}`,
        method: "GET"
      });
    }
  }

  /**
   * 添加旗舰&GPU版租户接口
   */
  public apiPostDaasTenantList(_data: any) {
    /**
     * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
     */
    const data = deepClone(_data);

    if (data.basicFormData && data.basicFormData.api_proxy) {
      data.basicFormData.api_proxy = encrypt(data.basicFormData.api_proxy);
    }

    return pandaRequest({
      url: `resource_pools/${ data.poolId }/mt_resources`,
      method: 'POST',
      data: {
        name: data.basicFormData.name,
        api_proxy: data.basicFormData.api_proxy,
        uri: data.basicFormData.manage_address,
        dedicated_line_gateway_address:data.basicFormData.cloud_line,
        credential: {
          username: data.basicFormData.manage_account,
          password: data.basicFormData.manage_password
          // password: encrypt(data.basicFormData.manage_password)
        },
        connection_info: {
          gateway: data.basicFormData.desktop_getaway_address
        },
        cloud_tenant_id: data.basicFormData.tenant,
        ad_info: {
          server_uri: data.adFormData.ad_adress,
          bind_dn: data.adFormData.ad_account,
          bind_password: data.adFormData.ad_password,
          search_base_dn: data.adFormData.ad_dn,
          search_filter: data.adFormData.ad_filiter
        },
       }
    });
  }

  /**
   * 编辑旗舰&GPU版租户接口
   */
  public apiPutDaasTenantList(_data: any) {
    /**
     * 先将数据深度拷贝出来，再做处理，可以避免处理时，ui上的数据也发生变动
     */
    const data = deepClone(_data);

    if (data.basicFormData && data.basicFormData.api_proxy) {
      data.basicFormData.api_proxy = encrypt(data.basicFormData.api_proxy);
    }

    return pandaRequest({
      url: `resource_pools/${ data.poolId }/mt_resources/${ data.id }`,
      method: 'PATCH',
      data: {
        name: data.basicFormData.name,
        api_proxy: data.basicFormData.api_proxy,
        uri: data.basicFormData.manage_address,
        dedicated_line_gateway_address:data.basicFormData.cloud_line,
        credential: {
          username: data.basicFormData.manage_account,
          password: data.basicFormData.manage_password
          // password: encrypt(data.basicFormData.manage_password)
        },
        connection_info: {
          gateway: data.basicFormData.desktop_getaway_address
        },
        // cloud_tenant_id: data.basicFormData.tenant,
        ad_info: {
          server_uri: data.adFormData.ad_adress,
          bind_dn: data.adFormData.ad_account,
          bind_password: data.adFormData.ad_password,
          search_base_dn: data.adFormData.ad_dn,
          search_filter: data.adFormData.ad_filiter
        },
       }
    });
  }

  /**
   * 获取租户列表接口
   */
  public apiGetTenantList(params: any) {
    return new Promise((resolve, reject) => {
      const rows = [];
      for (let i = 0; i < 10; i++) {
        rows.push({
          id: i,
          name: `租户${i}`
        });
      }
      if (params.page && params.page_size) {
        return resolve({
          rows: rows,
          total: 205
        });
      } else {
        return resolve(rows);
      }
    })
  }

  /**
   * 获取工单列表
   */
  public async apiGetWorkorders(params: any) {
    return pandaRequest({
      url: '/workorders',
      method: 'get',
      params
    });
  }

  /**
   * 批量处理工单
   */
  public async apiBatchHandleWorkorders(ids: Array<any>, type: any, approval_comments: any, approval_results: any) {
    // console.log(ids, type, approval_comments);
    switch(type) {
      case 'agree':
        for (let i = 0; i < ids.length; i++) {
          await pandaRequest({
            url: '/workorders/' + ids[i],
            method: "PATCH",
            data: {
              result_code: "agreed",
              result_detail: approval_comments
            }
          });
        }
        break;
      case 'reply':
        // for (let i = 0; i < ids.length; i++) {
        //   pandaRequest({
        //     url: '/workorders/' + ids[i],
        //     method: "PATCH",
        //     data: {
        //       result_code: "agreed",
        //       result_detail: approval_comments
        //     }
        //   });
        // }
        break;
      case 'hangUp':
        for (let i = 0; i < ids.length; i++) {
          await pandaRequest({
            url: '/workorders/' + ids[i],
            method: "PATCH",
            data: {
              result_code: "suspended",
              result_detail: approval_comments
            }
          });
        }
        break;
      case 'report':
        for (let i = 0; i < ids.length; i++) {
          await pandaRequest({
            url: '/workorders/' + ids[i],
            method: "PATCH",
            data: {
              declare: true
            }
          });
        }
        break;
      case 'refuse':
        for (let i = 0; i < ids.length; i++) {
          await pandaRequest({
            url: '/workorders/' + ids[i],
            method: "PATCH",
            data: {
              result_code: "rejected",
              result_detail: approval_comments
            }
          });
        }
        break;
      case 'again':
        for (let i = 0; i < ids.length; i++) {
          await pandaRequest({
            url: '/workorders/' + ids[i],
            method: "PATCH",
            data: {
              result_code: approval_results,
              result_detail: approval_comments
            }
          });
        }
        break;
    }
    return true;
  }

  /**
   * 批量删除工单
   */
  public async apiBatchDeleteWorkorder(itemList: Array<any>) {
    for (let i = 0; i < itemList.length; i++) {
      await pandaRequest({
        url: '/workorders/' + itemList[i].id,
        method: "DELETE"
      });
    }
    return true;
  }

  /**
   * 批量取消上报工单
   */
  public async apiCancelReportWorkorder(itemList: Array<any>) {
    for (let i = 0; i < itemList.length; i++) {
      await pandaRequest({
        url: '/workorders/' + itemList[i].id,
        method: "PATCH",
        data: {
          declare: false
        }
      });
    }
    return true;
  }

  /**
   * 获取资源池重名
   */
   public async apiGetResourcePool() {
    return await pandaRequest({
      url: '/resource_pools',
      method: 'GET'
    });
  }


  /**
   * 检查资源池重名
   */
  public async apiCheckResourcePoolName(name: string) {
    const poolList: any = await pandaRequest({
      url: '/resource_pools',
      method: 'GET'
    });

    const index = poolList.findIndex((pool: any) => pool.name === name);

    if (index != -1) {
      throw new Error(i18n.t('resource.resourcePoolNameRepeat').toString());
    } else {
      return true;
    }
  }

  /**
   * 检查USBRuleGroup重名
   */
    //  public async apiCheckUSBRuleGroupName(name: string) {
    //   const poolList: any = await pandaRequest({
    //     url: '/usb_rule_groups',
    //     method: 'GET'
    //   });
  
    //   const index = poolList.findIndex((pool: any) => pool.name === name);
    //   console.log(index);
    //   if (index != -1 || name === '默认USB规则组') {
    //     throw new Error(i18n.t('policy.message.USBRuleGroupNameOccupied').toString());
    //   } else {
    //     return true;
    //   }
    // }

    public async apiCheckUSBRuleGroupName(params: any) {
      const poolList: any = await pandaRequest({
        url: '/usb_rule_groups',
        method: 'GET',
        params
      });
      // console.log(poolList)
      if(poolList.total <= 0) {
        return true;
      }else {
        throw new Error(i18n.t('policy.message.USBRuleGroupNameOccupied').toString());
      }
    }

  /**
   * 获取概览页面
   */
   public apiGetOverview() {
    return pandaRequest({
      url: `/overviews/system`,
      method: 'GET',
    });
  }

  /**
   * 获取概览页面-租户管理员
   */
   public apiGetOverviewTenant() {
    return pandaRequest({
      url: `/overviews/tenant`,
      method: 'GET',
    });
  }

  public apiRecoverFromFile(backup_name: any, data: any) {
    return pandaRequest({
      url: "/backups/upload/" + backup_name,
      method: "put",
      data
    });
  }

  /**
   * 获取概览页面图表
   */
  public apiGetReports(params: any) {
    return pandaRequest({
      url: "/reports/current_sessions_count",
      method: "GET",
      params
    });
  }
  /**
   * return null
   */
   public apiGetNull(params: any) {
    return Promise.resolve({
      next: null,
      previous: null,
      rows: [],
      total: 0
    })
  }

  /**
   * 获取markdown列表
   */
  public apiGetMarkdownList(params: any) {
    return pandaRequest({
      url: "/faq",
      method: 'GET',
      params
    })
  }

  /**
   * 修改markdown
   */
   public apiPatchMarkdown(id: any, data: any) {
    return pandaRequest({
      url: "/faq/" + id,
      method: 'PATCH',
      data
    })
  }

  /**
   * 创建markdown
   */
   public apiPostMarkdownList(data: any) {
    return pandaRequest({
      url: "/faq",
      method: 'POST',
      data
    })
  }

  /**
   * 获取协议隐私
   */
  public apiGetAgreementList(params: any) {
    params.search = "Cloud Desktop"
    return pandaRequest({
      url: "/markdowns",
      method: 'GET',
      params
    })
  }

  /**
   * 修改协议隐私
   */
   public apiPatchAgreementList(id: any, data: any) {
    return pandaRequest({
      url: "/markdowns/" + id,
      method: 'PATCH',
      data
    })
  }

  /**
   * 上传markdown图片
   */
   public apiUploadImgs(data: any, headers: any) {
    return pandaRequest({
      url: "/markdowns/image/update",
      method: 'PUT',
      data,
      headers
    })
  }

  /**
   * 删除markdown
   */
   public apiDeleteMarkdown(data: any) {
    return pandaRequest({
      url: "/faq",
      method: 'DELETE',
      data
    })
  }

  /**
   * 客户端获取markdownList
   */
  public apiGetListForUser(data: any) {
    return pandaRequest({
      url: '/my_markdowns',
      method: 'GET',
      data
    })
  }

  /**
   * 桌面绑定终端
   */
   public apiPostDesktopBindClient(id: any, data: any) {
    return pandaRequest({
      url: "/desktops/ "+ id + "/bind_clients",
      method: 'POST',
      data
    })
  }

  /**
   * 租户管理员获取系统设置
   */
   public apiGetTenantSetting() {
    return pandaRequest({
      url: "/constances/cloud_tenant",
      method: 'get',
    })
  }

  /**
   * 租户管理员修改终端高级设置密码
   */
   public apiPatchTenantConsolePassword(data: any) {
    return pandaRequest({
      url: "/constances/cloud_tenant",
      method: 'POST',
      data
    })
  }

  /**
   * 普通版桌面池-绑定到租户
   */
   public apiUpdateCloudTenant(id: any, data: any) {
    return pandaRequest({
      url: "/desktops/" + id + "/update/cloud_tenant",
      method: 'POST',
      data
    })
  }

  /**
   * 本地显示版本日志
   */
   public apiGetVersionsLocal(params: any) {
     let data = {
        data: {
          total: 2, 
          next: null, 
          previous: null, 
          rows: [{
            display_product_model: i18n.t('clientVersionLog.windows'),
            product_model: 'x86_windows'
          },{
            display_product_model: i18n.t('clientVersionLog.x86'),
            product_model: 'x86_ubuntu'
          }]
        },
     }
    return new Promise((resolve: any,rejects: any) => {
      resolve(data.data);
    })
  }

  /**
   * 版本日志详情
   */
   public apiGetVersionsDetail(params: any) {
     delete params.search;
    return pandaRequest({
      url: "/version_instructions",
      method: 'GET',
      params
    })
  }

  /**
   * 创建版本日志
   */
   public apiCreateVersion(data: any) {
    return pandaRequest({  
      url: "/version_instructions",
      method: 'POST',
      data:data
    })
  }

  /**
   * 删除版本日志
   */
   public apiDeleteVersion(data: any) {
    return pandaRequest({
      url: "/version_instructions/delete",
      method: 'delete',
      data:data
    })
  }

  /**
   * 编辑版本日志
   */
   public apiEditVersion(id: any,data: any) {
    return pandaRequest({
      url: "/version_instructions/" + id,
      method: 'patch',
      data:data
    })
  }

  /**
   * 获取工作区列表
   * @param type 获取不同类型的工作区，面向订购、面向系统管理员、面向租户管理员
   * @param params 请求参数
   */
  public apiGetWorkSpace(type: "order" | "system" | "tenant", params: any) {
    return pandaRequest({
      url: `/${ type }/workareas`,
      method: 'GET',
      params
    })
  }

  /**
   * 获取工作区列表：通过workareauuid获取
   * @param type 获取不同类型的工作区，面向订购、面向系统管理员、面向租户管理员
   * @param params 请求参数
   */
   public apiGetWorkSpaceName(data: any) {
    return pandaRequest({
      url: `/system/workareas/names`,
      method: 'POST',
      data
    })
  }

  /**
   * 查询可用区
   */
  public apiGetAvailabilityZone(params: any) {
    return pandaRequest({
      url: 'admin/workareas/az_codes',
      method: 'get',
      params
    })
  }

  /**
   * 编辑工作区
   */
  public apiEditWorkSpace(data: any) {
    return pandaRequest({
      url: '/system/workareas/'+ data.id,
      method: 'patch',
      data: data
    })
  }
  // 设置共享工作区
  public apiPostSettingsWorkspac(data:any){ 
    return pandaRequest({
      url: `/system/workareas/${data.id}/guests`,
      method:"post",
      data:{
        cloud_tenant_names:data.name
      }
    })
  }
  // 获取共享工作区
  public apiGetworkareas(params:any){
    return pandaRequest({
      url: `/system/workareas/dass/guests`,
      method:"get",
      params
    })
  }
  // 取消共享工作区
  public apiDelSettingsWorkspac(data:any){ 
    return pandaRequest({
      url: `/system/workareas/${data.id}/guests`,
      method:"delete",
      data:{
        cloud_tenant_names:data.name
      }
    })
  }
}
